import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../controllers/device_controller.dart';
import '../../../widgets/safe_network_image.dart';

class DeviceView extends GetView<DeviceController> {
  const DeviceView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFEDF3FA),
      appBar: AppBar(
        title: Text('设备列表'),
        centerTitle: true,
        backgroundColor: Colors.transparent,
        foregroundColor: const Color(0xFF333333),
        elevation: 0,
        scrolledUnderElevation: 0,
        surfaceTintColor: Colors.transparent,
        shadowColor: Colors.transparent,
      ),
      body: Column(
        children: [
          // 可滚动的内容区域
          Expanded(
            child: Obx(
              () => RefreshIndicator(
                onRefresh: controller.refreshData,
                child: CustomScrollView(
                  slivers: [
                    SliverToBoxAdapter(
                      child: Column(
                        children: [
                          SizedBox(height: 20.h),
                          // 搜索栏 - 有白色背景
                          Padding(
                            padding: EdgeInsets.symmetric(horizontal: 20.w),
                            child: GestureDetector(
                              onTap: () => Get.toNamed('/search'),
                              child: Container(
                                height: 74.h,
                                decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.circular(14.r),
                                  boxShadow: [
                                    BoxShadow(
                                      color: Colors.black.withValues(
                                        alpha: 0.05,
                                      ),
                                      offset: const Offset(0, 2),
                                      blurRadius: 8,
                                    ),
                                  ],
                                ),
                                child: Row(
                                  children: [
                                    SizedBox(width: 46.w),
                                    Icon(
                                      Icons.search,
                                      size: 36.w,
                                      color: const Color(0xFF999999),
                                    ),
                                    SizedBox(width: 12.w),
                                    Expanded(
                                      child: Text(
                                        '通道名称',
                                        style: TextStyle(
                                          fontSize: 28.sp,
                                          color: const Color(0xFF999999),
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ),
                          SizedBox(height: 20.h),
                          // 域列表 - 横向滚动
                          _buildDomainList(),
                          SizedBox(height: 30.h),
                          // 统计信息和状态下拉 - 放在筛选标签下面，无背景
                          Padding(
                            padding: EdgeInsets.symmetric(horizontal: 20.w),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Expanded(
                                  child: Obx(
                                    () => Text(
                                      '共${controller.totalChannels.value}台设备，在线 ${controller.onlineChannels.value} 台，离线 ${controller.offlineChannels.value} 台',
                                      style: TextStyle(
                                        fontSize: 28.sp,
                                        color: const Color(0xFF999999),
                                      ),
                                      overflow: TextOverflow.ellipsis,
                                      maxLines: 1,
                                    ),
                                  ),
                                ),
                                // 状态下拉框
                                PopupMenuButton<int>(
                                  onSelected:
                                      (int index) =>
                                          controller.changeStatus(index),
                                  offset: Offset(0, 40.h),
                                  elevation: 8,
                                  shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(12.r),
                                  ),
                                  color: Colors.white,
                                  padding: EdgeInsets.zero,
                                  itemBuilder:
                                      (BuildContext context) => [
                                        PopupMenuItem<int>(
                                          value: 0,
                                          child: SizedBox(
                                            width: 120.w,
                                            child: Text(
                                              '全部状态',
                                              style: TextStyle(
                                                fontSize: 26.sp,
                                                color:
                                                    controller
                                                                .selectedStatusIndex
                                                                .value ==
                                                            0
                                                        ? const Color(
                                                          0xFF047FF7,
                                                        )
                                                        : const Color(
                                                          0xFF333333,
                                                        ),
                                              ),
                                            ),
                                          ),
                                        ),
                                        PopupMenuItem<int>(
                                          value: 1,
                                          child: SizedBox(
                                            width: 120.w,
                                            child: Text(
                                              '在线',
                                              style: TextStyle(
                                                fontSize: 26.sp,
                                                color:
                                                    controller
                                                                .selectedStatusIndex
                                                                .value ==
                                                            1
                                                        ? const Color(
                                                          0xFF047FF7,
                                                        )
                                                        : const Color(
                                                          0xFF333333,
                                                        ),
                                              ),
                                            ),
                                          ),
                                        ),
                                        PopupMenuItem<int>(
                                          value: 2,
                                          child: SizedBox(
                                            width: 120.w,
                                            child: Text(
                                              '离线',
                                              style: TextStyle(
                                                fontSize: 26.sp,
                                                color:
                                                    controller
                                                                .selectedStatusIndex
                                                                .value ==
                                                            2
                                                        ? const Color(
                                                          0xFF047FF7,
                                                        )
                                                        : const Color(
                                                          0xFF333333,
                                                        ),
                                              ),
                                            ),
                                          ),
                                        ),
                                      ],
                                  child: Container(
                                    padding: EdgeInsets.symmetric(
                                      horizontal: 8.w,
                                      vertical: 8.h,
                                    ),
                                    child: Row(
                                      mainAxisSize: MainAxisSize.min,
                                      children: [
                                        Text(
                                          controller.statusOptions[controller
                                              .selectedStatusIndex
                                              .value],
                                          style: TextStyle(
                                            fontSize: 28.sp,
                                            color: const Color(0xFF333333),
                                          ),
                                        ),
                                        SizedBox(width: 8.w),
                                        Icon(
                                          Icons.keyboard_arrow_down,
                                          size: 23.w,
                                          color: const Color(0xFF666666),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          SizedBox(height: 20.h),
                        ],
                      ),
                    ),
                    // 设备列表 - 每个列表项有白色背景
                    if (controller.filteredChannelList.isEmpty &&
                        !controller.isLoading.value)
                      SliverToBoxAdapter(child: _buildEmptyState())
                    else
                      SliverList(
                        delegate: SliverChildBuilderDelegate(
                          (context, index) {
                            if (index ==
                                controller.filteredChannelList.length) {
                              return _buildLoadMoreIndicator();
                            }

                            final channel =
                                controller.filteredChannelList[index];
                            return _buildChannelItem(channel);
                          },
                          childCount:
                              controller.filteredChannelList.length +
                              (controller.hasMoreData.value ? 1 : 0),
                        ),
                      ),
                    // 底部间距
                    SliverToBoxAdapter(child: SizedBox(height: 20.h)),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 构建通道项
  Widget _buildChannelItem(Map<String, dynamic> channel) {
    final ptzType = channel['ptzType']?.toString();
    final isOnline = channel['status'] == 'ON';
    final channelName = channel['name']?.toString() ?? '未知设备';
    final snapUrl = channel['snapUrl']?.toString();
    final hsId = channel['hsId']?.toString() ?? '';

    // 根据ptzType和isOnline获取对应的图片路径
    String? getDeviceImage() {
      if (ptzType == null || ptzType.isEmpty) {
        return null; // 未知类型不显示图片
      }

      final ptzTypeInt = int.tryParse(ptzType);
      if (ptzTypeInt == null) {
        return null; // 无效的ptzType不显示图片
      }

      switch (ptzTypeInt) {
        case 1: // 球机
          return isOnline
              ? 'assets/images/device/球机-在线.png'
              : 'assets/images/device/球机-离线.png';
        case 2: // 半球
          return isOnline
              ? 'assets/images/device/球机-在线.png' // 半球暂时使用球机图片
              : 'assets/images/device/球机-离线.png';
        case 3: // 固定枪机
        case 4: // 遥控枪机
          return isOnline
              ? 'assets/images/device/抢机-在线.png'
              : 'assets/images/device/抢机-离线.png';
        default: // 0 - 未知或其他
          return null; // 未知类型不显示图片
      }
    }

    final deviceImagePath = getDeviceImage();

    return Padding(
      padding: EdgeInsets.fromLTRB(20.w, 0, 20.w, 20.h),
      child: GestureDetector(
        onTap: () {
          // 跳转到设备详情页面，传递设备ID和通道ID
          Get.toNamed(
            '/device-detail',
            arguments: {
              'hsId': hsId,
              'deviceId': channel['deviceId']?.toString() ?? '',
              'channelId': channel['channelId']?.toString() ?? '',
              'deviceName': channelName,
            },
          );
        },
        child: AnimatedContainer(
          duration: const Duration(milliseconds: 200),
          padding: EdgeInsets.all(30.w),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(14.r),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withValues(alpha: 0.05),
                offset: const Offset(0, 2),
                blurRadius: 8,
              ),
            ],
          ),
          child: Row(
            children: [
              // 设备图标 - 根据ptzType和isOnline显示对应图片
              if (deviceImagePath != null)
                Image.asset(deviceImagePath, width: 32, height: 32)
              else
                // 未知类型时显示默认图标
                Container(
                  width: 32,
                  height: 32,
                  decoration: BoxDecoration(
                    color:
                        isOnline
                            ? const Color(0xFF0ACA00).withValues(alpha: 0.1)
                            : const Color(0xFFD8D8D8).withValues(alpha: 0.1),
                    shape: BoxShape.circle,
                  ),
                  child: Icon(
                    Icons.videocam,
                    size: 16,
                    color:
                        isOnline
                            ? const Color(0xFF0ACA00)
                            : const Color(0xFF999999),
                  ),
                ),
              SizedBox(width: 12),
              // 设备信息
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      channelName,
                      style: TextStyle(
                        fontSize: 28.sp,
                        fontWeight: FontWeight.w500,
                        color: const Color(0xFF333333),
                      ),
                    ),
                    SizedBox(height: 8.h),
                    Row(
                      children: [
                        AnimatedContainer(
                          duration: const Duration(milliseconds: 300),
                          width: 16.w,
                          height: 16.h,
                          decoration: BoxDecoration(
                            color:
                                isOnline
                                    ? const Color(0xFF0ACA00)
                                    : const Color(0xFFD8D8D8),
                            shape: BoxShape.circle,
                          ),
                        ),
                        SizedBox(width: 10.w),
                        Text(
                          isOnline ? '在线' : '离线',
                          style: TextStyle(
                            fontSize: 24.sp,
                            color:
                                isOnline
                                    ? const Color(0xFF0ACA00)
                                    : const Color(0xFF999999),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              // 视频缩略图 - 使用安全的网络图片组件
              if (snapUrl != null && snapUrl.isNotEmpty)
                SafeNetworkImageWithPlay(
                  imageUrl: snapUrl,
                  width: 212.w,
                  height: 142.h,
                  borderRadius: BorderRadius.circular(16.r),
                  onTap: () {
                    // 跳转到设备详情页面
                    Get.toNamed(
                      '/device-detail',
                      arguments: {
                        'hsId': hsId,
                        'deviceId': channel['deviceId']?.toString() ?? '',
                        'channelId': channel['channelId']?.toString() ?? '',
                        'deviceName': channelName,
                      },
                    );
                  },
                ),
            ],
          ),
        ),
      ),
    );
  }

  // 空状态
  Widget _buildEmptyState() {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 100.h),
      child: Center(
        child: Column(
          children: [
            Icon(
              Icons.devices_other,
              size: 80.w,
              color: const Color(0xFFCCCCCC),
            ),
            SizedBox(height: 20.h),
            Text(
              '暂无设备',
              style: TextStyle(fontSize: 28.sp, color: const Color(0xFF999999)),
            ),
          ],
        ),
      ),
    );
  }

  // 加载更多指示器
  Widget _buildLoadMoreIndicator() {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 20.h),
      child: Center(
        child: Obx(
          () =>
              controller.isLoading.value
                  ? SizedBox(
                    width: 20.w,
                    height: 20.h,
                    child: const CircularProgressIndicator(strokeWidth: 2),
                  )
                  : Text(
                    '已加载全部设备',
                    style: TextStyle(
                      fontSize: 24.sp,
                      color: const Color(0xFF999999),
                    ),
                  ),
        ),
      ),
    );
  }

  /// 构建域列表（横向滚动）
  Widget _buildDomainList() {
    return SizedBox(
      height: 74.h,
      child: Obx(() {
        // 构建域选项列表（全部 + 域列表）
        final allDomains = [
          {'id': '', 'name': '全部域'},
          ...controller.domainList,
        ];

        return ListView.builder(
          padding: EdgeInsets.symmetric(horizontal: 20.w),
          scrollDirection: Axis.horizontal,
          itemCount: allDomains.length,
          itemBuilder: (context, index) {
            final domain = allDomains[index];
            final isSelected = controller.selectedDomainIndex.value == index;
            final domainName = domain['name']?.toString() ?? '未知域';

            return GestureDetector(
              onTap: () => controller.changeDomain(index),
              child: AnimatedContainer(
                duration: const Duration(milliseconds: 200),
                height: 74.h,
                margin: EdgeInsets.only(
                  right: index < allDomains.length - 1 ? 30.w : 0,
                ),
                padding: EdgeInsets.symmetric(horizontal: 24.w),
                decoration: BoxDecoration(
                  color: isSelected ? const Color(0xFF047FF7) : Colors.white,
                  borderRadius: BorderRadius.circular(16.r),
                  border: Border.all(
                    color:
                        isSelected
                            ? const Color(0xFF047FF7)
                            : const Color(0xFFE0E0E0),
                    width: 1,
                  ),
                  boxShadow: [
                    BoxShadow(
                      color:
                          isSelected
                              ? const Color(0xFF047FF7).withValues(alpha: 0.3)
                              : Colors.black.withValues(alpha: 0.05),
                      offset: const Offset(0, 2),
                      blurRadius: isSelected ? 8 : 4,
                    ),
                  ],
                ),
                child: Center(
                  child: Text(
                    domainName,
                    style: TextStyle(
                      fontSize: 28.sp,
                      fontWeight:
                          isSelected ? FontWeight.w500 : FontWeight.normal,
                      color:
                          isSelected ? Colors.white : const Color(0xFF999999),
                    ),
                  ),
                ),
              ),
            );
          },
        );
      }),
    );
  }
}
